<template>
  <div class="tabsContent">
    <div class="tableCon">
      <px-form ref="formRef" class="custom-form-ui inspection-form" :model="queryParams" label-position="right" label-width="120px">
        <px-form-item label="检测结果">
          <px-select v-model="queryParams.detectResult" filterable clearable placeholder="请选择检测结果">
            <px-option v-for="item in detectResultData" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="检测机构">
          <px-select v-model="queryParams.detectOrganization" filterable clearable placeholder="请选择检测机构">
            <px-option v-for="item in organizationArr" :key="item.itemValue" :label="item.itemName" :value="item.itemValue" />
          </px-select>
        </px-form-item>
        <px-form-item label="负责人">
          <px-select-v2 v-model="queryParams.responsiblePersonId" filterable clearable :options="peopleList" placeholder="请选择负责人" />
        </px-form-item>
        <px-form-item label="报告日期" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form>
      <px-row :gutter="10" style="margin-bottom: 16px">
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_HAVCWATERTEST_IMPORT_MCHW'" type="primary" icon="" @click="handleImport">导入报告</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_HAVCWATERTEST_IMPORT_HISTORY_MCHW'" type="primary" plain icon="" @click="importHistory">导入历史</px-button>
        </px-col>
        <!-- <px-col :span="1.5">
          <px-button type="primary" plain icon="" @click="handleExport">导出报告</px-button>
        </px-col> -->
      </px-row>
      <px-scrollbar>
        <px-table
          :data="tableData"
          class="inspection-table"
          size="small"
          height="calc(100vh -400px)"
          border
          :header-cell-class-name="tableHeaderColor"
          @selection-change="selectionChange"
        >
          <!-- <px-table-column type="selection" width="40" align="center" /> -->
          <!-- <px-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column> -->
          <px-table-column label="MIDDLE TEMPERATURE SYSTEM" align="center">
            <px-table-column label="Date" align="left">
              <px-table-column prop="reportTime" label="Y-M-D" />
            </px-table-column>
            <px-table-column label="pH" align="right">
              <px-table-column prop="date" label="7.5-8.8" align="right">
                <template #default="scope">
                  <div>
                    <px-icon v-if="scope.row.MCHWConfig1.ooc" :color="scope.row.MCHWConfig1.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                      ><Top v-if="scope.row.MCHWConfig1.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig1.oocArrow === 'D'" /></px-icon
                    >{{ scope.row.MCHWConfig1.testValue }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
            <px-table-column label="Zn" align="right">
              <px-table-column label="" align="right">
                <px-table-column prop="date" label="< 1" align="right">
                  <template #default="scope">
                    <div>
                      <px-icon v-if="scope.row.MCHWConfig2.ooc" :color="scope.row.MCHWConfig2.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                        ><Top v-if="scope.row.MCHWConfig2.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig2.oocArrow === 'D'" /></px-icon
                      >{{ scope.row.MCHWConfig2.testValue }}
                    </div>
                  </template>
                </px-table-column>
              </px-table-column>
            </px-table-column>
            <px-table-column label="Iron" align="right">
              <px-table-column label="as Fe" align="right">
                <px-table-column prop="date" label="< 3ppm" align="right">
                  <template #default="scope">
                    <div>
                      <px-icon v-if="scope.row.MCHWConfig3.ooc" :color="scope.row.MCHWConfig3.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                        ><Top v-if="scope.row.MCHWConfig3.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig3.oocArrow === 'D'" /></px-icon
                      >{{ scope.row.MCHWConfig3.testValue }}
                    </div>
                  </template>
                </px-table-column>
              </px-table-column>
            </px-table-column>
            <px-table-column label="Turbidity" align="right">
              <px-table-column label="NTU" align="right">
                <px-table-column prop="date" label="< 10NTU" align="right">
                  <template #default="scope">
                    <div>
                      <px-icon v-if="scope.row.MCHWConfig4.ooc" :color="scope.row.MCHWConfig4.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                        ><Top v-if="scope.row.MCHWConfig4.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig4.oocArrow === 'D'" /></px-icon
                      >{{ scope.row.MCHWConfig4.testValue }}
                    </div>
                  </template>
                </px-table-column>
              </px-table-column>
            </px-table-column>
            <px-table-column label="TPC" align="right">
              <px-table-column label="cfu/ml" align="right">
                <px-table-column prop="date" label="< 1,000" align="right">
                  <template #default="scope">
                    <div>
                      <px-icon v-if="scope.row.MCHWConfig5.ooc" :color="scope.row.MCHWConfig5.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                        ><Top v-if="scope.row.MCHWConfig5.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig5.oocArrow === 'D'" /></px-icon
                      >{{ scope.row.MCHWConfig5.testValue }}
                    </div>
                  </template>
                </px-table-column>
              </px-table-column>
            </px-table-column>
            <px-table-column label="Conductivity" align="right">
              <px-table-column label="us/cm" align="right">
                <px-table-column prop="date" label="N/A" align="right">
                  <template #default="scope">
                    <div>
                      <px-icon v-if="scope.row.MCHWConfig6.ooc" :color="scope.row.MCHWConfig6.oocArrow === 'U' ? '#EF7577' : '#10B981'"
                        ><Top v-if="scope.row.MCHWConfig6.oocArrow === 'U'" /><Bottom v-if="scope.row.MCHWConfig6.oocArrow === 'D'" /></px-icon
                      >{{ scope.row.MCHWConfig6.testValue }}
                    </div>
                  </template>
                </px-table-column>
              </px-table-column>
            </px-table-column>
          </px-table-column>
          <px-table-column label="检测机构" prop="detectOrganization" align="center" show-overflow-tooltip />
          <px-table-column label="采样人" prop="samplePerson" align="center" show-overflow-tooltip />
          <px-table-column label="负责人" prop="responsiblePerson" align="center" show-overflow-tooltip />
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
      </px-scrollbar>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <div class="bgDom" />
    <div class="spcCon">
      <px-form ref="spcFormRef" class="custom-form-ui inspection-form" :model="querySpcParams" label-position="right" label-width="120px">
        <px-form-item label="SPC时间" style="width: 450px">
          <px-date-picker
            v-model="dateRangeSpc"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="shortcuts"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button type="primary" @click="querySpc">查询</px-button>
        <px-button @click="resetSpc">重置</px-button>
      </px-form>
      <div v-loading="chartsLoading">
        <div v-if="spcOptionList.length > 0" class="spc_con">
          <div v-for="item in spcOptionList" :key="item.id" class="spc_item">
            <spcCharts ref="spcChartsDom" :key="chartsKey" :title="item.title" :width="600" :optionData="item" color="#3B82F6" />
          </div>
        </div>
        <px-empty v-else :image-size="150" />
      </div>
    </div>
    <uploadFiles v-if="dialogVisible" v-model="dialogVisible" @submit="submitHandler" />
    <px-dialog v-model="historyDialogVisible" width="60%" title="导入历史" align-center>
      <px-table :data="historyData" border class="inspection-table">
        <px-table-column label="序号" type="index" width="80" />
        <px-table-column prop="originalName" label="文件名称" show-overflow-tooltip />
        <px-table-column prop="createTime" label="Date" width="180" />
        <px-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <px-tooltip content="下载" placement="top">
              <px-button link type="primary" icon="Download" @click="handleDownload(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="historytotal > 0"
        v-model:page="historyPageNum"
        v-model:limit="historyPageSize"
        style="margin-bottom: -10px"
        :total="historytotal"
        @pagination="getHistoryList"
      />
    </px-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, reactive, toRefs, nextTick } from "vue";
import spcCharts from "@/views/machine/components/spcCharts/index.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { spcquerySpcAnalysis } from "@/api/spc";
import { waterTestList, queryImportHistoryListPage, queryChildByTypeCodeAndItemValue } from "@/api/machineClass";
import uploadFiles from "../uploadFiles/index.vue";
import ExcelJS from "exceljs"; // 引入exceljs, 用于生成excel文件
import { saveAs } from "file-saver"; // 引入file-saver, 用于保存文件

const { proxy }: any = getCurrentInstance();

const props = defineProps({
  activeName: {
    type: String,
    default: () => ""
  },
  // 弹窗类型 view 查看 add 新增 edit 编辑
  pageType: {
    type: String,
    default: () => ""
  },
  tabsOption: {
    type: Array,
    default: () => []
  }
});

const state = reactive<any>({
  organizationArr: [],
  spcDataList: [],
  spcOptionList: [],
  chartsLoading: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    subsystem: props.activeName
  },
  querySpcParams: {},
  total: 0,
  tableData: [],
  selectIds: [],
  viewSparePartsVisible: false,
  drawerType: "add",
  checkTaskId: "",
  peopleList: [] // 筛选的人员列表
});

const { selectIds, organizationArr, spcDataList, spcOptionList, chartsLoading, queryParams, total, tableData, peopleList, querySpcParams } =
  toRefs(state);

const detectResultData = ref([
  {
    label: "合格",
    value: "1"
  },
  {
    label: "不合格",
    value: "0"
  }
]);

const chartsKey = ref(Date.now());

const historyDialogVisible = ref(false);
const historyData = ref([]);

const dateRange = ref<any>([]);
const dateRangeSpc = ref<any>([]);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const spcChartsDom = ref();

const tableData1 = ref([
  {
    date: "2016-05-03",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  },
  {
    date: "2016-05-02",
    name: "Tom",
    address: "No. 189, Grove St, Los Angeles"
  }
]);

const exportChartToExcel = (chartRef, range, workbook, worksheet) => {
  console.log(chartRef, "++++++++++++++++++++++++++");
  const base64Image = chartRef.getDataURL({
    pixelRatio: 2, // 导出图片的分辨率比例，默认为1
    backgroundColor: "#fff" // 导出图片的背景色
  });
  let image = workbook.addImage({
    base64: base64Image, // 图片的base64编码
    extension: "png" // 图片的扩展名
  });
  worksheet.addImage(image, range); // 将图片添加到工作表中
};

const handleExport = async () => {
  const workbook = new ExcelJS.Workbook(); // 创建工作簿
  const worksheet = workbook.addWorksheet("Sheet1"); // 添加工作表

  // 第1行
  const row1 = worksheet.getRow(2);
  row1.font = { bold: true }; // 设置表头字体加粗
  row1.alignment = { vertical: "middle", horizontal: "center" }; // 设置表头居中对齐
  row1.height = 30; // 设置表头行高

  const header1 = worksheet.getCell(`B2`);
  worksheet.mergeCells(`B2:G2`);
  header1.value = "MIDDLE TEMPERATURE SYSTEM"; // 设置表头内容

  // 第2行
  const row2 = worksheet.getRow(3);
  row2.font = { bold: true }; // 设置表头字体加粗
  row2.alignment = { vertical: "middle", horizontal: "center" }; // 设置表头居中对齐
  row2.height = 20; // 设置表头行高
  // 第2行
  const row3 = worksheet.getRow(4);
  row2.font = { bold: true }; // 设置表头字体加粗
  row2.alignment = { vertical: "middle", horizontal: "center" }; // 设置表头居中对齐
  row2.height = 20; // 设置表头行高

  const header3 = worksheet.getCell(`B3`);
  worksheet.mergeCells(`B3:B4`);
  header3.value = "Date"; // 设置表头内容
  const header4 = worksheet.getCell(`C3`);
  worksheet.mergeCells(`C3:C4`);
  header4.value = "PH"; // 设置表头内容
  const header5 = worksheet.getCell(`D3`);
  header5.value = "Zn"; // 设置表头内容
  header5.font = { bold: true }; // 设置表头字体加粗
  header5.alignment = { vertical: "middle", horizontal: "center" }; // 设置表头居中对齐
  const header6 = worksheet.getCell(`D4`);
  header6.value = ""; // 设置表头内容
  const header7 = worksheet.getCell(`E3`);
  header7.value = "Iron"; // 设置表头内容
  const header8 = worksheet.getCell(`E4`);
  header8.value = "as Fe"; // 设置表头内容
  const header9 = worksheet.getCell(`F3`);
  header9.value = "Turbidity"; // 设置表头内容
  const header10 = worksheet.getCell(`F4`);
  header10.value = "NTU"; // 设置表头内容
  const header11 = worksheet.getCell(`G3`);
  header11.value = "TPC"; // 设置表头内容
  const header12 = worksheet.getCell(`G4`);
  header12.value = "cfu/ml"; // 设置表头内容
  const header13 = worksheet.getCell(`H3`);
  header13.value = "Conductivity"; // 设置表头内容
  const header14 = worksheet.getCell(`H4`);
  header14.value = "us/cm"; // 设置表头内容

  // 导出表格数据
  // const tableRange = { tl: { col: 0, row: 60 }, br: { col: 3, row: 80 } };
  // tableData1.forEach((item, index) => {
  //   worksheet.addRow([item.date, item.name, item.address]);
  // });
  const params = proxy.addDateRange(queryParams.value, dateRange.value, "reportStart", "reportEnd");
  params.pageNum = 1;
  params.pageSize = 9999; // 查询数据总条数
  const data = await waterTestList(params);
  let dataList = data?.data ? data.data : [];
  dataList.map((item: any) => {
    if (item.testResult && item.testResult.length > 0) {
      item.testResult.forEach((el: any) => {
        item[el.key] = el;
      });
    }
    return item;
  });
  worksheet.addRows([
    // [],
    ["", "Y-M-D", "7.5-8.8", "< 1", "< 3ppm", "< 10NTU", "< 1000", "N/A"],
    ...dataList.map(item => [
      "",
      item.reportTime,
      item.MCHWConfig1.testValue,
      item.MCHWConfig2.testValue,
      item.MCHWConfig3.testValue,
      item.MCHWConfig4.testValue,
      item.MCHWConfig5.testValue,
      item.MCHWConfig6.testValue
    ])
  ]);
  // const columns = [
  //   { header: "D/M/Y", key: "date" },
  //   { header: "7.5-8.8", key: "name" },
  //   { header: "<1200", key: "address" }
  // ];
  // worksheet.addTable({
  //   ref: `A${4}`,
  //   rows: tableData1.value.map(item => [item.date, item.name, item.address]),
  //   columns: [
  //     {
  //       name: "D/M/Y"
  //     },
  //     {
  //       name: "7.5-8.8"
  //     },
  //     {
  //       name: "<1200"
  //     }
  //   ],
  //   headerRow: true,
  //   totalsRow: false,
  //   style: {
  //     theme: "TableStyleLight1",
  //     showRowStripes: true
  //   }
  // });
  const showCharts = spcOptionList.value.filter((item: any) => item.pointValues && item.pointValues.length);
  if (showCharts && showCharts.length) {
    const echartsDom1 = await spcChartsDom.value[1].getEcharts();
    // const echartsDom2 = await spcChartsDom.value[2].getEcharts();
    const startRow = dataList.length + 7;
    // console.log("spcChartsDom.value", spcChartsDom.value);
    // for (let i = 0; i < spcDataList.value.length; i++) {
    //   let startRow = dataList.length + 7;
    //   let addNum = i * 20;
    //   // let echartsDom = await spcChartsDom.value[i].getEcharts();
    //   exportChartToExcel(await spcChartsDom.value[i].getEcharts(), `A${startRow + addNum}:J${startRow + addNum}`, workbook, worksheet);
    //   // echartsDom = null;
    // }
    const addNum = 20;
    // 导出第一个图表
    exportChartToExcel(echartsDom1, `A${startRow}:J${startRow + 20}`, workbook, worksheet);
    // exportChartToExcel(echartsDom2, `L${startRow}:U${startRow + 20}`, workbook, worksheet);
  }
  // 导出第二个图表
  // exportChartToExcel("chart2", "A25:J45", workbook, worksheet);

  // 生成excel文件并保存
  workbook.xlsx.writeBuffer().then(function (buffer) {
    saveAs(
      new Blob([buffer], {
        type: "application/octet-stream"
      }),
      "xchart.xlsx"
    );
  });
};

const shortcuts = [
  {
    text: "本日",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "本季度",
    value: () => {
      const end = new Date();
      const start = new Date();
      let currenMonth = start.getMonth();
      let quarter = Math.floor((currenMonth + 3) / 3) - 1;
      start.setMonth(quarter * 3, 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  }
];

const tableHeaderColor = ({ row, column, rowIndex, columnIndex }) => {
  if (rowIndex === 1) {
    return "bg1";
  }
  if (rowIndex === 3 || rowIndex === 2) {
    return "bg2";
  }
  return "bg0";
};

// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.checklistId) {
      selectIds.value.push(item.checklistId);
    }
  });
};

// 查询
const queryTable = async () => {
  const params = proxy.addDateRange(queryParams.value, dateRange.value, "reportStart", "reportEnd");
  const data = await waterTestList(params);
  let dataList = data?.data ? data.data : [];
  dataList.map((item: any) => {
    if (item.testResult && item.testResult.length > 0) {
      item.testResult.forEach((el: any) => {
        item[el.key] = el;
      });
    }
    return item;
  });
  tableData.value = dataList;
  total.value = data?.total;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [];
  queryParams.value = {
    subsystem: props.activeName,
    pageNum: 1,
    pageSize: 10
  };
  queryTable();
};
// 查询SPC
const querySpc = () => {
  getSpcCharts(spcDataList.value);
};
// 重置
const resetSpc = () => {
  dateRangeSpc.value = initSpcDate();
  getSpcCharts(spcDataList.value);
};
const handleImport = async () => {
  dialogVisible.value = true;
};

const historyPageNum = ref(1);
const historyPageSize = ref(10);
const historytotal = ref(0);

const getHistoryList = async () => {
  const data = await queryImportHistoryListPage({ pageNum: historyPageNum.value, pageSize: historyPageSize.value });
  historyData.value = data?.data;
  historytotal.value = data?.total;
};

const importHistory = () => {
  historyDialogVisible.value = true;
  nextTick(() => {
    getHistoryList();
  });
};

const handleDownload = (row: any) => {
  // 下载文件
  console.log(row.originalName);
  const url = row.fileUrl;
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", row.originalName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const dialogVisible = ref(false);
const submitHandler = async () => {
  const message = "上传成功";
  PxMessage.success(message);
  await queryTable();
};

/** 导出按钮操作 */
// function handleExport() {
// const dictIds = [];
// dictIds.push(...ids.value);
//console.log(dictIds);
// liquidExport({ ids: dictIds }).then((response: any) => {
//   PxMessage({
//     message: "导出成功",
//     type: "success"
//   });
// });
// downloadParams.value.ids = selectIds.value;
// const params = { ids: dictIds };
// proxy.download("post", "/operation/api/v1/water/hazardWasteIn/export", params, "水质检测-CW检测报告.xlsx");
// }

const getTitle = (item: any) => {
  return (
    `${props.activeName.split("Config")[0]}` + "(" + spcDataList.value.find((i: any) => JSON.parse(i.itemDesc).spc_job === item.jobId).itemName + ")"
  );
};
const getSpcCharts = async (obj: any) => {
  const jobIDs = [];
  spcOptionList.value = [];
  chartsLoading.value = true;
  obj.forEach((item: any) => {
    jobIDs.push(JSON.parse(item.itemDesc).spc_job);
  });
  const params = {
    jobIdList: [...jobIDs],
    timePeriod: "day",
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1],
    ignoreTimeValidate: true
  };
  try {
    const res: any = await spcquerySpcAnalysis(params);
    // spcOptionList.value = res ? res : [];

    // 需要展示的SPC 可替换下方jobIdS
    // const showSpcIds = [
    //   "SPC_QA_CWConfig10",
    //   "SPC_QA_CWConfig11",
    //   "SPC_QA_CWConfig12",
    //   "SPC_QA_CWConfig1",
    //   "SPC_QA_CWConfig2",
    //   "SPC_QA_CWConfig3",
    //   "SPC_QA_CWConfig4",
    //   "SPC_QA_CWConfig7",
    //   "SPC_QA_CWConfig8"
    // ];
    // 过滤
    // const arr = res.filter((item: any) => jobIDs.indexOf(item.jobId) !== -1 && item.pointValues && item.pointValues.length > 0); // 过滤出有数据的
    const arr = res.filter((item: any) => jobIDs.indexOf(item.jobId) !== -1); // 过滤出有数据的
    spcOptionList.value = arr.map((item: any) => {
      item.startTime = dateRangeSpc.value[0];
      item.endTime = dateRangeSpc.value[1];
      item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
      return {
        ...item,
        title: getTitle(item)
      };
    });
    chartsKey.value = Date.now();
    chartsLoading.value = false;
    console.log(spcOptionList.value, "spcOptionList");
  } catch (error) {
    chartsLoading.value = false;
  }
};

const init = async () => {
  queryChildByTypeCodeAndItemValue({
    value: "DU01",
    typeCode: "MCTS"
  }).then((res: any) => {
    organizationArr.value = res ? res : [];
  });
  const cwData = await queryChildByTypeCodeAndItemValue({
    value: props.activeName,
    typeCode: "MCTS"
  });
  spcDataList.value = cwData ? cwData : [];
  getSpcCharts(spcDataList.value);
  peopleList.value = await getEmployeeIdAndName(["MACHINE"]);
  queryTable();
};

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${lastYear}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} 23:59:59`]; // 近一年时间范围
};

onMounted(() => {
  dateRangeSpc.value = initSpcDate();
  init();
});
</script>
<style lang="scss" scoped>
.tabsContent {
  margin-top: 10px;

  .tableCon {
    padding: 0 24px 16px;

    :deep(.px-table__header) {
      thead {
        .bg0 {
          background-color: #e7eef8 !important;
        }

        .bg1 {
          background-color: #fef5e6 !important;
        }

        .bg2 {
          background-color: #e8f8f3 !important;
        }
      }
    }
  }

  .bgDom {
    height: 16px;
    background-color: #f0f2f5;
  }

  .spcCon {
    padding: 16px 24px 0;

    .spc_con {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      justify-content: space-between;
      min-width: 1300px;

      .spc_item {
        width: 49%;
        height: 468px;
        margin-bottom: 16px;
        border-radius: 4px;
      }
    }
  }

  :deep(.px-table .px-table__header-wrapper th) {
    background-color: #e7eef8;
  }
}
</style>
